package com.example.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: sn
 * @Desc something
 * @Date: 2021/9/16
 */
public class NioServer {

    public static void main(String[] args) throws IOException,
            InterruptedException {
        List<SocketChannel> clients = new ArrayList<SocketChannel>();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//不阻塞
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
        while (true){
            SocketChannel client = serverSocketChannel.accept();
            System.out.println("accept...");
            if (client != null) {
//不阻塞
                client.configureBlocking(false);
                clients.add(client);
            }else {
                TimeUnit.SECONDS.sleep(2);
            }
//看看保存的clients里面又没客户端发送数据
            for (SocketChannel client1 : clients) {
//读取数据
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int length = 0;
                while ((length = client1.read(byteBuffer)) > 0) {
                    byteBuffer.flip();
                   // log.info(new String(byteBuffer.array(), 0, length));
                    System.out.println(new String(byteBuffer.array(), 0, length));
                    byteBuffer.clear();
                }
            }
        }
    }
}
